from django.db import models
from django.utils import timezone


class Room(models.Model):
    id = models.CharField(max_length=100, primary_key=True)
    name = models.CharField(max_length=300)
    user_id = models.CharField(max_length=100)
    status = models.IntegerField(default=1)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'room'

    def serialize(self):
        return {
            'id': self.id,
            'name': self.name,
            'user_id': self.user_id,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S'),
            'path': self.id,
            'data': [],
        }

    @classmethod
    def create_room(cls, room_id, name, user_id):
        room, created = cls.objects.get_or_create(id=room_id, defaults={'name': name, 'user_id': user_id})
        if not created:
            room.update_time = timezone.now()
            room.save(update_fields=['update_time'])
            return False
        return True

    @classmethod
    def get_active_rooms_by_user_id(cls, user_id):
        return cls.objects.filter(user_id=user_id, status=1).order_by('update_time')

    @classmethod
    def update_room(cls, room_id, **kwargs):
        cls.objects.filter(id=room_id).update(**kwargs, update_time=timezone.now())

    @classmethod
    def delete_room(cls, room_id):
        room = cls.objects.filter(id=room_id).first()
        if room:
            room.status = 0
            room.save()

    @classmethod
    def delete_rooms_by_user_id(cls, user_id):
        cls.objects.filter(user_id=user_id).update(status=0)
